/**
 * Created by sxwu on 14-2-14.
 */
/**
 * 路由工具类
 */

var config = require('../config');
var enms = require('../lib/enmus');
var dateformat = require('dateformat');
var crypto = require('crypto');

/**
 * 公用数据
 */
exports.retdata = function(request) {
    return {
        url: request.path,
        title: ' ',
        subtitle:'',
        nickname:'',//昵称
        success:false, //true,false
        retType:'alert-info',
        info:'',
        lastlogindate:'',
        lastloginip:'',
        roleinfo:null
    };
};
exports.operlog=function(request){
    return{
        id:-1,
        userid:-1,
        username:'',
        nickname:'',
        opertype:'',
        opercont:'',
        operip:'',
        operdate:''
    };
}
exports.operlogdata = function(request) {
    return {
        retdata:this.retdata(request),
        operlog:this.operlog(request)
    };
};

exports.authlistemun = [{
    'key': -1,
    'value': '无限制'
},{
    'key': 2,
    'value': '无认证：一键上网'
}, {
    'key': 4,
    'value': '无认证：摇一摇'
}, {
    'key': 8,
    'value': '微信：关注公众号'
}, {
    'key': 16,
    'value': '微信：扫描二维码直接上网'
}, {
    'key': 32,
    'value': '微博认证'
}];

exports.getspecialauthlist=function(authnumber){
    var authlist="";
    if(authnumber==-1)
        return this.authlistemun[0].value;

    for(var i=1; i < this.authlistemun.length; i++)
    {
        if((authnumber& this.authlistemun[i].key)!==0)
        {
            if(authlist=="")
                authlist=this.authlistemun[i].value;
            else
                authlist=authlist+"<BR>"+this.authlistemun[i].value;
        }
    }
    return authlist;
}

exports.getauthlist=function(authnumber){
    var authlist="";
    for(var i=0; i < this.authlistemun.length; i++)
    {
        if(authlist=="")
            authlist=this.authlistemun[i].value;
        else
            authlist=authlist+"<BR>"+this.authlistemun[i].value;
    }
    return authlist;
}

exports.statlistemun = [{
    'key': -1,
    'value': '无限制'
},{
    'key': 2,
    'value': '我的广告点击统计'
}, {
    'key': 4,
    'value': '顾客上网方式统计'
}];

exports.getspecialstatlist=function(statnumber){
    var statlist="";
    if(statnumber==-1)
        return this.statlistemun[0].value;

    for(var i=1; i < this.statlistemun.length; i++)
    {
        if((statnumber& this.statlistemun[i].key)!==0)
        {
            if(statlist=="")
                statlist=this.statlistemun[i].value;
            else
                statlist=statlist+"<BR>"+this.statlistemun[i].value;
        }
    }
    return statlist;
}

exports.getstatlist=function(statnumber){
    var statlist="";
    for(var i=0; i < this.statlistemun.length; i++)
    {
        if(statlist=="")
            statlist=this.statlistemun[i].value;
        else
            statlist=statlist+"<BR>"+this.statlistemun[i].value;
    }
    return statlist;
}
exports.getrolenum=function(param)
{
    if(Object.prototype.toString.call(param)!== '[object Array]' )
    {
        return param;
    }
    else
    {
        if(param[0]=="-1")
            return -1;
        else
           return eval(param.join("+"));
    }
};

exports.getchildroleid=function(param)
{
    if(Object.prototype.toString.call(param)!== '[object Array]' )
    {
        return param;
    }
    else
    {
        if(param[0]=="-1")
            return -1;
        else
            return param.join(",");
    }
};


exports.role=function(request){
    return{
        id:-1,
        rolename:'',
        usernumber:0,
        wifinumber:0,
        apnumber:0,
        adnumber:0,
        statnumber:0,
        authnumber:0,
        validmonth:0,
        fee:0,
        descs:'',
        flag:0,
        childroleid:''
    };
}
exports.rolesdata = function(request) {
    return {
        retdata:this.retdata(request)
        ,role:this.role(request)
    };
};

exports.notify=function(request){
    return{
        id:-1,
        fromuserid:0,
        touserid:0,
        createdate:0,
        msgcontent:'',
        notifytype:'',
        expiredate:'',
        tonickname:'',
        level:''
    };
}
exports.notifydata = function(request) {
    return {
        retdata:this.retdata(request)
        ,notify:this.notify(request)
    };
};

exports.viruser = function(request) {
    return {
        id:-1,
        roleid:-1,
        username:'',
        userpwd:'',
        usernick:'',
        userflag:0,
        companyname:'',
        email:'',
        phonenumber:'',
        regdate:'',
        expiredate:'',
        lastlogindate:'',
        lastloginip:'',
        proxyid:-1

    };
};
exports.viruserdata = function(request) {
    return {
        retdata:this.retdata(request),
        viruser:this.viruser(request)
    };
};

exports.virwifiinfo=function(request){
  return {
      id:-1,
      userid:-1,
      wifissid:'',
      wifiauthtype:0,
      wifiauthhour:0,
      wifiauthbrand:0,
      wifiredirecturl:'',
      weixincode:'',
      wifipassdomain:''
  };
};

exports.virwifiinfodata = function(request) {
    return {
        retdata:this.retdata(request),
        virwifiinfo:this.virwifiinfo(request)
    };
};

exports.indexdata = function(request) {
    return {
        retdata:this.retdata(request)
    };
};

var operlog=require('../models/operlog.js');

exports.getClientIp=function(req) {
    return req.headers['x-forwarded-for'] ||
        req.connection.remoteAddress ||
        req.socket.remoteAddress ||
        req.connection.socket.remoteAddress;
};
exports.writeoperlog=function(request,type,action){
    var operlogdata = this.operlog(request);
    operlogdata.userid=request.session.admin.id;
    operlogdata.username=request.session.admin.username;
    operlogdata.nickname=request.session.admin.nickname;
    operlogdata.opertype=type;
    operlogdata.opercont=action;
    operlogdata.operip=this.getClientIp(request);
    operlog.insert(operlogdata, function(error,results) {

    });
}
///////////////////////////////////////////////////////////////////

exports.data = function(request) {
    return {
        url: request.path,
        title: '',
        usernick:'',//昵称
        config: config,
        md5: function(text) {
            return require('crypto').createHash('md5').update(text).digest('hex');
        },
        dateFormat: function(date) {
            return dateformat(date, "yyyy-mm-dd");
        },
        datetimeFormat: function(date) {
            return dateformat(date, "yyyy-mm-dd hh:mm:ss");
        }
    };
};

/**
 * 前台数据
 */
exports.front_data = function(request) {
    return {
        url: request.path,
        title: '无线路由管理平台',
        subtitle:'',
        usernick:'',//昵称
        usertype:'',
        errDesp:'',
        //config: config,

        md5: function(text) {
            return require('crypto').createHash('md5').update(text).digest('hex');
        },
        dateFormat: function(date) {
            return dateformat(date, "yyyy-mm-dd");
        },
        datetimeFormat: function(date) {
            return dateformat(date, "yyyy-mm-dd hh:mm:ss");
        }
    };
};
exports.index_data = function(request) {
    return {
        front_data:this.front_data(request)
    };
};

exports.wifi_info = function(request) {
    return {
        wifiuserid:-1,
        wifissid:'',
        wifiauthtype:0,
        wifiauthhour:0,
        wifiauthbrand:0,
        wifiredirecturl:'',
        weixincode:'',
        wifipassdomain:''

    };
};
exports.wifi_data = function(request) {
    return {
        front_data:this.front_data(request),
        wifiinfo:this.wifi_info(request)

    };
};

exports.ap_info = function(request) {
    return {
        userid:-1,
        wifiid:-1,
        apname:"",
        apmac:'',
        apsn:'',
        apdes:'',
        aplocation:'',
        apcustomernum:'',
        apflag:0,
        updatetime:'',
        groupenable:0,
        devid:0,
        groupidforssid:''

    };
};
exports.ap_data = function(request) {
    return {
        front_data:this.front_data(request),
        apinfo:this.ap_info(request)

    };
}

//customerinfo
exports.customerinfo=function(request) {
    return {
        wifiid:0,
        userid:0,
        custphone:'',
        custname:'',
        custregdatetime:'',
        custtotalflow:0,
        custtotaltime:0,
        custflag:1,
        custmac:'',
        custip:'',
        apmac:''
    };
};


exports.customerlogdata=function(request) {
    return {
        custlogid:0,
        customerid:0,
        logauthtype:'',
        logcustip:'',
        logcustmac:'',
        logcurrentflow:'',
        logcurrenttime:'',
        logupdate:'',
        logdowndate:'',
        sessionid:''
    };
};


//广告表的字段结构体
exports.ad_info = function(request) {
    return {
        userid:-1,
        adname:"",
        adtype:0,
        adpicurl:'',
        adlinkurl:'',
        adpicurl1:'',
        adlinkurl1:'',
        adpicurl2:'',
        adlinkurl2:'',
        adhtml:'',
        adhtmlsrc:'',
        adactivedate:'',
        adexpiredate:'',
        addevtype:''

    };
};
exports.ad_data = function(request) {
    return {
        front_data:this.front_data(request),
        adinfo:this.ad_info(request)

    };
}




exports.stat_range = function(request) {
    return {
        userid:-1,
        logauthtype:'',
        begindate:'',
        enddate:''

    };
};

exports.statrange = function(request) {
    return {
        front_data:this.front_data(request),
        statrange:this.stat_range(request)

    };
}

var cipheriv = function (en, code, data) {
    var buf1 = en.update(data, code), buf2 = en.final();
    var r = new Buffer(buf1.length + buf2.length);
    buf1.copy(r); buf2.copy(r, buf1.length);
    return r;
};
exports.EncryptDES=function (data, key, vi) {
    return data = cipheriv(_crypto.createCipheriv('des', key, vi), 'utf8', data).toString('base64');
};
exports.DecryptDES=function (data, key, vi) {
    return cipheriv(_crypto.createDecipheriv('des', key, vi), 'base64', data) .toString('utf8');
};

exports.AP_COM = function() {
    return {
        apComRet:{
            apComRetHead: {
                retFlag: 0,
                reason:''
            },
            apComRetCont:
            {
                vnoId:'',
                ssid:'',
                passUrl:'*.weibo.com||*.qq.com',
                desKey:'123456',
                duration:0,
                traffic:-99,
                rate:0,
                onlineState:'',
                group:0,
                devid:0,
                sessionId:''
                //groupidforssid:''
            }
        }
    };
}


var cryptoCfg="mima=adwifi";
exports.checkVaild=function(info){
    return 0;
    if(info.apComHead.apMac=="00:11:22:33:44:55" )
    {
        return 0;
    }
    if(typeof(info.apComHead.apMac)=="undefined" || typeof(info.apComHead.token)=="undefined")
    {
        return 1;
    }

    if(info.apComHead.token!=="" && info.apComHead.apMac!=="")
    {
        var crypttoken=info.apComHead.token;
        var cryptMac=crypto.createHash('md5').update(info.apComHead.apMac+cryptoCfg).digest('hex');
        if(crypttoken.toLowerCase()!==cryptMac.toLowerCase())
        {
            return 1;
        }
        else
        {
            return 0;
        }
    }
    return 1;

}
exports.checkVaildForURL=function(request){
    return 0;
    if(request.query.apmac=="00:11:22:33:44:55" )
    {
        return 0;
    }

    if(typeof(request.query.apmac)=="undefined" || typeof(request.query.apmac)=="undefined")
    {
        console.log("checkVaildForURL:request.query.apmac undefined");
        return 1;
    }

    if(request.query.token!=="" &&  request.query.apmac!=="")
    {
        var crypttoken=request.query.token;
        var cryptMac=crypto.createHash('md5').update(request.query.apmac+cryptoCfg).digest('hex');
        if(crypttoken.toString().toLowerCase()!==cryptMac.toString().toLowerCase())
        {
            console.log("checkVaildForURL:request.query.apmac+cryptoCfg:"+request.query.apmac+cryptoCfg);
            console.log("checkVaildForURL:request.query.apmac:"+request.query.apmac);
            console.log("checkVaildForURL:cryptMac:"+cryptMac.toString().toLowerCase());
            console.log("checkVaildForURL:crypttoken:"+crypttoken.toString().toLowerCase());
            return 1;
        }
        else
        {
            return 0;
        }
    }
    return 1;
}